package com.community.owner.service.impl;

import com.community.common.constant.HttpStatus;
import com.community.common.core.page.PageDomain;
import com.community.common.core.page.TableDataInfo;
import com.community.common.core.page.TableSupport;
import com.community.common.core.redis.RedisCache;
import com.community.common.utils.PageUtils;
import com.community.common.utils.ServletUtils;
import com.community.common.utils.StringUtils;
import com.community.common.utils.sql.SqlUtil;
import com.community.owner.domain.OwnerVehicleRecord;
import com.community.owner.domain.enums.SmartCode;
import com.community.owner.handle.redis.RedisConst;
import com.community.owner.mapper.OwnerVehicleRecordMapper;
import com.community.owner.service.OwnerVehicleRecordService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class OwnerVehicleRecordServiceImpl implements OwnerVehicleRecordService {


    @Autowired
    private OwnerVehicleRecordMapper vehicleRecordMapper;

    @Autowired
    private RedisCache redisCache;


    private static final Integer CACHE_TIMEOUT = 24 * 60; // 24小时

    //使用redis缓存车辆出入记录
    @Override
    public TableDataInfo selectAllVehicleRecordsWithPage(OwnerVehicleRecord ownerVehicleRecord) {
        String cacheKey = generateCacheKey(ownerVehicleRecord);
        log.info("生成的缓存key: {}", cacheKey);

        // 尝试从缓存获取TableDataInfo
        TableDataInfo cachedResult = redisCache.getCacheObject(cacheKey);
        if (cachedResult != null) {
            log.info("✅ 从Redis缓存获取分页车辆记录数据");
            return cachedResult;
        }

        // 使用若依的分页查询
        startPage(); // 在服务层调用分页
        List<OwnerVehicleRecord> records = vehicleRecordMapper.selectAllVehicleRecords(ownerVehicleRecord);
        TableDataInfo result = getDataTable(records);

        // 缓存分页结果
        redisCache.setCacheObject(cacheKey, result, CACHE_TIMEOUT, TimeUnit.MINUTES);
        log.info("分页车辆记录数据已缓存到Redis",result);

        return result;
    }

    private String generateCacheKey(OwnerVehicleRecord record) {
        StringBuilder keyBuilder = new StringBuilder("vehicle:record:page:");

        // 分页参数
        keyBuilder.append("pageNum=").append(ServletUtils.getParameterToInt("pageNum", 1)).append(":");
        keyBuilder.append("pageSize=").append(ServletUtils.getParameterToInt("pageSize", 10)).append(":");

        // 搜索条件
        if (StringUtils.isNotEmpty(record.getGateDevice())) {
            keyBuilder.append("gate=").append(record.getGateDevice().trim()).append(":");
        }
        if (StringUtils.isNotEmpty(record.getOwnerName())) {
            keyBuilder.append("owner=").append(record.getOwnerName().trim()).append(":");
        }
        if (record.getOwnerCommunity() != null && StringUtils.isNotEmpty(record.getOwnerCommunity().getName())) {
            keyBuilder.append("community=").append(record.getOwnerCommunity().getName().trim()).append(":");
        }

        if (keyBuilder.length() > "vehicle:record:page:".length()) {
            keyBuilder.setLength(keyBuilder.length() - 1);
        } else {
            keyBuilder.append("all");
        }

        return keyBuilder.toString();
    }

    // 需要继承BaseService或手动引入分页相关方法
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }



    @Override
    public void clearVehicleRecordCache() {
        try {
            // 清除所有车辆记录相关的缓存
            Collection<String> keys = redisCache.keys(RedisConst.VEHICLE_RECORD_LIST_KEY + "*");
            if (keys != null && !keys.isEmpty()) {
                redisCache.deleteObject(keys);
                log.info("成功清除车辆记录缓存，清除key数量: {}", keys.size());
            } else {
                log.info("未找到车辆记录相关的缓存key");
            }
        } catch (Exception e) {
            log.error("清除车辆记录缓存失败", e);
        }
    }
}
